<!--
/**
 *
 * SugarCRM Community Edition is a customer relationship management program developed by
 * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
 *
 * SuiteCRM is an extension to SugarCRM Community Edition developed by SalesAgility Ltd.
 * Copyright (C) 2011 - 2018 SalesAgility Ltd.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by the
 * Free Software Foundation with the addition of the following permission added
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along with
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 *
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
 * reasonably feasible for technical reasons, the Appropriate Legal Notices must
 * display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM".
 */

-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang='en'>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
		<title>Sugar Rest Example</title>
<!-- Dependency -->

<!--CSS file (default YUI Sam Skin) -->
<link type="text/css" rel="stylesheet" href="http://yui.yahooapis.com/2.6.0/build/datatable/assets/skins/sam/datatable.css">

<!-- Dependencies -->

<script src="http://yui.yahooapis.com/2.6.0/build/yahoo/yahoo-min.js"></script>

<!-- Used for Custom Events and event listener bindings -->
<script src="http://yui.yahooapis.com/2.6.0/build/event/event-min.js"></script>

<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/element/element-beta-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/datasource/datasource-min.js"></script>

<!-- OPTIONAL: JSON Utility (for DataSource) -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/json/json-min.js"></script>

<!-- OPTIONAL: Connection Manager (enables XHR for DataSource) -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/connection/connection-min.js"></script>

<!-- OPTIONAL: Get Utility (enables dynamic script nodes for DataSource) -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/get/get-min.js"></script>

<!-- OPTIONAL: Drag Drop (enables resizeable or reorderable columns) -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/dragdrop/dragdrop-min.js"></script>

<!-- OPTIONAL: Calendar (enables calendar editors) -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/calendar/calendar-min.js"></script>

<!-- Source files -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/datatable/datatable-min.js"></script>

<script>

var SugarRest = function(){}
SugarRest.proxy_url  = 'Rest_Proxy.php';
SugarRest.server_url = 'http://localhost/[Sugar Path]/service/v2/rest.php'
SugarRest.leadFields = [ 'id','do_not_call', 'first_name', 'last_name', 'status', 'phone_work', 'lead_source', 'salutation', 'primary_address_country', 'primary_address_city','primary_address_state', 'primary_address_postalcode', 'department', 'title', 'account_name'];
SugarRest.moduleFields = {};
SugarRest.logResponse = function(o){
	data = YAHOO.lang.JSON.parse(o.responseText);
	//console.log(data);
	return data;
}


SugarRest.call = function(fun, args, callback, params){
	//console.log(args);
	query = SugarRest.getQuery(fun, args);
	YAHOO.util.Connect.asyncRequest('POST', SugarRest.proxy_url  , {success:callback, failure:callback, argument:params}, query);
}

SugarRest.getQuery = function(fun, args){
	query = 'method=' + fun + '&input_type=json&response_type=json';
	if(args != null){
		m = YAHOO.lang.JSON.stringify(args);
		query += '&rest_data=' + m;
	}
	return query;
}

SugarRest.getServerInfo =  function(){
	//console.log('Getting Server Info');
	SugarRest.call('get_server_info', '', SugarRest.test);
}

SugarRest.login =  function(name, password, application){
	//console.log(name);
	SugarRest.call('md5', password, SugarRest.performLogin, {name:name ,application:application});

}

SugarRest.performLogin = function(o){

	//console.log('Logging In');
	var loginData = [{
		user_name: o.argument.name,
		password:YAHOO.lang.JSON.parse(o.responseText)
	},o.argument.application];
	SugarRest.call('login', loginData, SugarRest.getUserId);
}

SugarRest.getUserId =  function(o){
	data  = YAHOO.lang.JSON.parse(o.responseText);
	SugarRest.session = data.id;
	SugarRest.call('get_user_id', SugarRest.session, SugarRest.setUserId);
}

SugarRest.setUserId = function(o){
	SugarRest.user_id =YAHOO.lang.JSON.parse(o.responseText);
	SugarRest.getModuleFields('Leads', SugarRest.leadFields);
}
SugarRest.getModuleFields = function(module, fields){
	SugarRest.call('get_module_fields', [SugarRest.session, module, fields], SugarRest.setModuleFields);
}

SugarRest.setModuleFields = function(o){
	data  = SugarRest.logResponse(o);
	console.log(data.module_fields);
	SugarRest.moduleFields[data.module_name] = data.module_fields;
	SugarRest.InlineCellEditing();
}
SugarRest.getLeadsQuery = function(){
	var data = [SugarRest.session, 'Leads', " leads.do_not_call = 0 AND leads.status != 'Converted' AND leads.status != 'Dead' AND leads.assigned_user_id = '" + SugarRest.user_id + "' ", '', 0, SugarRest.leadFields, [{
		'name': 'email_addresses',
		'value': ['id', 'email_address', 'opt_out', 'primary_address',]
	}], 500, 0];
	q =  SugarRest.getQuery('get_entry_list', data, SugarRest.test);
	console.log(q);
	return q;
}

SugarRest.getFeeds = function(){
	var data = [SugarRest.session, 'SugarFeed', "", '', 0, ['id', 'name', 'description', 'link_url', 'link_type', 'created_by', 'date_entered', 'related_id', 'related_module'], [], 500, 0];
	SugarRest.call('get_entry_list', data, SugarRest.test);

}


SugarRest.getLeads = function(){
	q = SugarRest.getLeadsQuery();
	 var myCallback = function() {
            this.set("sortedBy", null);
            this.onDataReturnAppendRows.apply(this,arguments);
        };
     SugarRest.myDataSource.sendRequest(q,
                {
            success : myCallback,
            failure : myCallback,
            scope : SugarRest.myDataTable
     });
}

SugarRest.saveChange = function(callback, newValue){
	var r = this.getRecord();
	var column = this.getColumn();
	var id = r._oData['name_value_list.id'];
	name = column.key.replace('name_value_list.', '');
    name = name.replace('.value','');
    
	if(name == 'do_not_call'){
		newValue = (newValue == 'Do Not Call')? 1: 0;
	}
	//console.log("New Value:" + newValue);
	if(name == 'status' && newValue == 'Converted'){
		SugarRest.window = window.open('');
		callback();
		SugarRest.seamless_login_url = 'module=Leads&action=ConvertLead&record=' + id;
		SugarRest.call('seamless_login', SugarRest.session, SugarRest.seamless, 'module=Leads&action=ConvertLead&record=' + id );
		return;
	}
	fields = {};
	fields['id'] = id;
	fields[name] = newValue;

	data = [SugarRest.session, 'Leads',fields ];
	SugarRest.call('set_entry', data, SugarRest.savedChanges, {
		callback: callback,
		newValue: newValue
	});

}

SugarRest.savedChanges = function(o){
	//console.log(o);
	callback = o.argument.callback;
	 var r = YAHOO.lang.JSON.parse(o.responseText);
     if (r.id) {
         callback(true, o.argument.newValue);
     } else {
        //console.log('save failed');
        callback();
     }

}

SugarRest.editRecord = function(module, id){
	query = 'module=' + module +'&record=' + id + '&action=EditView';
	SugarRest.seamless_login_url = query;
	SugarRest.call('seamless_login', SugarRest.session, SugarRest.seamless, query);

}

SugarRest.seamless = function(o){
	if (o.responseText == 1) {
		surl = SugarRest.server_url +'/index.php?' + SugarRest.seamless_login_url + '&MSID=' +SugarRest.session;
		//console.log('opening:' + surl);
		SugarRest.window.location.href = surl;
	}

}


SugarRest.buildColumnDefs = function(){


}



 SugarRest.InlineCellEditing = function(){
 	var statusOptions = [];
	for(i in SugarRest.moduleFields.Leads.status.options){
		statusOptions[statusOptions.length] = {'label': SugarRest.moduleFields.Leads.status.options[i].name, 'value':SugarRest.moduleFields.Leads.status.options[i].value};
	}
	var salutationOptions = [];
	for(i in SugarRest.moduleFields.Leads.salutation.options){
		salutationOptions[salutationOptions.length] = {'label': SugarRest.moduleFields.Leads.salutation.options[i].name, 'value':SugarRest.moduleFields.Leads.salutation.options[i].value};
	}
 	 SugarRest.myColumnDefs = [
			{key:"name_value_list.id",formatter:SugarRest.editLink, label:'Edit'},
           // {key:"name_value_list.salutation.value",sortable:true, label:SugarRest.moduleFields.Leads.salutation.label, editor: new YAHOO.widget.DropdownCellEditor({asyncSubmitter:SugarRest.saveChange, dropdownOptions:salutationOptions})},
			{key:"name_value_list.first_name.value",sortable:true, label:SugarRest.moduleFields.Leads.first_name.label, editor: new YAHOO.widget.TextboxCellEditor({asyncSubmitter:SugarRest.saveChange})},
			{key:"name_value_list.last_name.value",sortable:true, label:SugarRest.moduleFields.Leads.last_name.label ,editor: new YAHOO.widget.TextboxCellEditor({asyncSubmitter:SugarRest.saveChange})},
            {key:"name_value_list.phone_work.value", formatter:SugarRest.callLink, label:SugarRest.moduleFields.Leads.phone_work.label},
			{key:"name_value_list.status.value",sortable:true, label:SugarRest.moduleFields.Leads.status.label, editor: new YAHOO.widget.DropdownCellEditor({asyncSubmitter:SugarRest.saveChange, dropdownOptions:statusOptions})},
			{key:"name_value_list.account_name.value",sortable:true, label:SugarRest.moduleFields.Leads.account_name.label, editor: new YAHOO.widget.TextboxCellEditor({asyncSubmitter:SugarRest.saveChange})},
			//{key:"name_value_list.department.value",sortable:true, label:SugarRest.moduleFields.Leads.department.label, editor: new YAHOO.widget.TextboxCellEditor({asyncSubmitter:SugarRest.saveChange})},
			{key:"name_value_list.title.value",sortable:true, label:SugarRest.moduleFields.Leads.title.label, editor: new YAHOO.widget.TextboxCellEditor({asyncSubmitter:SugarRest.saveChange})},
			{key:"name_value_list.primary_address_city.value",sortable:true, label:'City', editor: new YAHOO.widget.TextboxCellEditor({asyncSubmitter:SugarRest.saveChange})},
			{key:"name_value_list.primary_address_state.value",sortable:true, label:'State', editor: new YAHOO.widget.TextboxCellEditor({asyncSubmitter:SugarRest.saveChange})},
			//{key:"name_value_list.primary_address_country.value",sortable:true, label:'Country', editor: new YAHOO.widget.TextboxCellEditor({asyncSubmitter:SugarRest.saveChange})},
			{key:"name_value_list.primary_address_postalcode.value",sortable:true, label:'Postal', editor: new YAHOO.widget.TextboxCellEditor({asyncSubmitter:SugarRest.saveChange})},
			//{key:"name_value_list.lead_source.value", label:SugarRest.moduleFields.Leads.lead_source.label},
			{key:"name_value_list.do_not_call.value",formatter:SugarRest.checkboxField, label:SugarRest.moduleFields.Leads.do_not_call.label, editor: new YAHOO.widget.DropdownCellEditor({asyncSubmitter:SugarRest.saveChange, dropdownOptions:['Call', 'Do Not Call']})},
        ];

  SugarRest.myDataSource = new YAHOO.util.DataSource(SugarRest.proxy_url );
  SugarRest.myDataSource.connMethodPost = true;
  SugarRest.myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
  SugarRest.myDataSource.connXhrMode = "queueRequests";

  SugarRest.myDataSource.responseSchema = {
    resultsList : "entry_list", // String pointer to result data
  };
 SugarRest.myDataSource.responseSchema['fields'] = SugarRest.myColumnDefs;



  SugarRest.myDataTable = new YAHOO.widget.DataTable("cellediting",   SugarRest.myColumnDefs,

          SugarRest.myDataSource, {initialRequest:SugarRest.getLeadsQuery()});
 // Set up editing flow
	        var highlightEditableCell = function(oArgs) {
	            var elCell = oArgs.target;
	            if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
	                this.highlightCell(elCell);
	            }
	        };
	        SugarRest.myDataTable.subscribe("cellMouseoverEvent", highlightEditableCell);
	        SugarRest.myDataTable.subscribe("cellMouseoutEvent", SugarRest.myDataTable.onEventUnhighlightCell);
	        SugarRest.myDataTable.subscribe("cellClickEvent", SugarRest.myDataTable.onEventShowCellEditor);

 }
        // Custom formatter for "address" column to preserve line breaks
  SugarRest.formatAddress = function(elCell, oRecord, oColumn, oData) {
            elCell.innerHTML = "<pre class=\"address\">" + oData + "</pre>";
  };

   SugarRest.editLink = function(elCell, oRecord, oColumn, oData) {
            elCell.innerHTML = "<input type='button' onclick='SugarRest.window = window.open(); SugarRest.editRecord(\"Leads\", \"" + oData + "\");' value='Edit'>";
  };

   SugarRest.callLink = function(elCell, oRecord, oColumn, oData) {
            elCell.innerHTML = "<a href='callto:" + oData+ "'>"+ oData+ "</a>";
  };

   SugarRest.checkboxField = function(elCell, oRecord, oColumn, oData) {
   			checked = (oData == '1')? ' CHECKED ': '';
   			elCell.innerHTML = "<input type='checkbox' " + checked + ">";
  };








</script>
	</head>
	<body class="yui-skin-sam">
		<div id="dialog1">
		<div class="hd">Please Login <span id="error"></span></div>
		<div class="bd">
				<label for="username">User Name:</label><input id='username' type="text" name="username" value="will"/>
				<label for="password">Password:</label><input id='password' type="password" name="password" value="will"/>
				<input type="button" value="Login" onclick='SugarRest.login(document.getElementById("username").value,document.getElementById("password").value , "Sugar Rest Demo")'>
		</div></div>


		<div id="cellediting"></div>
	</body>
</html>
